package com.itwc.websocketdemo.service;

import com.itwc.websocketdemo.entity.AiPost;
import com.itwc.websocketdemo.entity.SysUser;
import com.itwc.websocketdemo.entity.UserPostRelation;
import com.itwc.websocketdemo.mapper.AiPostMapper;
import com.itwc.websocketdemo.mapper.SysUserMapper;
import com.itwc.websocketdemo.mapper.UserPostRelationMapper;
import com.itwc.websocketdemo.websocket.NativeWebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 推文服务类
 */
@Slf4j
@Service
public class PostService {

    
    @Autowired
    private AiPostMapper aiPostMapper;
    
    @Autowired
    private SysUserMapper sysUserMapper;
    
    @Autowired
    private UserPostRelationMapper userPostRelationMapper;
    
    @Autowired
    private WebSocketService webSocketService;
    
    /**
     * 发布推文并推送给所有用户
     */
    @Transactional
    public AiPost publishPost(AiPost post) {
        // 设置默认值
        LocalDateTime now = LocalDateTime.now();
        post.setCreateTime(now);
        post.setUpdateTime(now);
        post.setPublishTime(now);
        post.setViewCount(0);
        post.setLikeCount(0);
        post.setCommentCount(0);
        post.setDeleted(0);
        post.setStatus(1);
        
        // 设置默认作者ID（如果没有提供的话）
        if (post.getAuthorId() == null) {
            post.setAuthorId(1L); // 默认管理员ID
        }
        
        if (post.getIsFeatured() == null) post.setIsFeatured(0);
        if (post.getIsTop() == null) post.setIsTop(0);
        if (post.getSortOrder() == null) post.setSortOrder(0);
        
        // 插入推文
        aiPostMapper.insertPost(post);
        log.info("推文发布成功，ID: {}, 标题: {}", post.getId(), post.getTitle());
        
        // 获取所有活跃用户
        List<SysUser> allUsers = sysUserMapper.selectAllActiveUsers();
        
        // 创建用户推文关联记录
        List<UserPostRelation> relations = new ArrayList<>();
        for (SysUser user : allUsers) {
            UserPostRelation relation = new UserPostRelation();
            relation.setUserId(user.getUserId());
            relation.setPostId(post.getId());
            relation.setIsRead(0);  // 未读
            relation.setIsPushed(0);  // 未推送
            relation.setCreateTime(now);
            relation.setUpdateTime(now);
            relations.add(relation);
        }
        
        // 批量插入关联记录
        if (!relations.isEmpty()) {
            userPostRelationMapper.batchInsertRelations(relations);
            log.info("为 {} 个用户创建推文关联记录", relations.size());
        }
        
        // 获取在线用户并通过原生WebSocket推送
        Set<Long> onlineUserIds = webSocketService.getOnlineUserIds();
        
        for (Long userId : onlineUserIds) {
            // 通过原生WebSocket推送推文通知
            String userIdStr = String.valueOf(userId);
            NativeWebSocketServer.sendPostNotification(userIdStr, post.getId(), post.getTitle(), 
                "您有新的推文：" + post.getTitle());
            
            // 推送未读数量更新
            int unreadCount = userPostRelationMapper.countUnreadPosts(userId);
            NativeWebSocketServer.sendUnreadCountUpdate(userIdStr, unreadCount);
        }
        
        // 标记在线用户的推文为已推送
        for (Long userId : onlineUserIds) {
            userPostRelationMapper.markAsPushed(userId, post.getId());
        }
        
        log.info("推文推送完成，在线用户数: {}", onlineUserIds.size());
        
        return post;
    }
    
    /**
     * 获取推文详情
     */
    public AiPost getPostById(Long postId) {
        return aiPostMapper.selectPostById(postId);
    }
    
    /**
     * 获取所有推文
     */
    public List<AiPost> getAllPosts() {
        return aiPostMapper.selectAllActivePosts();
    }
    
    /**
     * 获取用户的推文列表（包含未读状态）
     */
    public List<UserPostRelation> getUserPostsWithReadStatus(Long userId) {
        return userPostRelationMapper.selectUserPostsWithReadStatus(userId);
    }
    
    /**
     * 标记推文为已读
     */
    @Transactional
    public void markPostAsRead(Long userId, Long postId) {
        userPostRelationMapper.markAsRead(userId, postId);
        
        // 更新推文浏览量
        aiPostMapper.updateViewCount(postId);
        
        // 通过原生WebSocket发送更新后的未读数量
        int unreadCount = userPostRelationMapper.countUnreadPosts(userId);
        if (webSocketService.isUserOnline(userId)) {
            NativeWebSocketServer.sendUnreadCountUpdate(String.valueOf(userId), unreadCount);
        }
        
        log.info("用户 {} 标记推文 {} 为已读，当前未读数量: {}", userId, postId, unreadCount);
    }
    
    /**
     * 获取用户未读推文数量
     */
    public int getUnreadCount(Long userId) {
        return userPostRelationMapper.countUnreadPosts(userId);
    }
}